﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Ionic.Zip;
using CRMBiz;
using System.Data;
using CRMWeb.Utilities.Context;
using CRMBiz.Report;
using CRMFramework;

namespace CRMWeb.WebServices.Report
{
    /// <summary>
    /// Summary description for ExportToCSV
    /// </summary>
    public class ExportToCSV : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string strReportName = context.Request.Params["strReport"].ToString();
            DataTable dt = null;
            string strState = string.Empty;
            string strFilePath = string.Empty;
            string comesfrom = string.Empty;
            string strQuery = string.Empty;
            string strGroupType = string.Empty;
            string strdays = string.Empty;
            string strGroupName = string.Empty;

            try
            {
                if (strReportName == "Test2014")
                {
                    strState = context.Request.Params["strState"].ToString();
                    comesfrom = context.Request.Params["strcomesfrom"].ToString();
                    strFilePath = System.Web.HttpContext.Current.Server.MapPath("~/ExportGroupData/reportTest2014.csv");
                    dt = ReportHandler.GetTest2014Report(strState, comesfrom);
                }
                else if (strReportName == "GroupData")
                {
                    strFilePath = System.Web.HttpContext.Current.Server.MapPath("/ExportGroupData/groupdata.csv");

                    string strcols = " ContactID,FirstName,SurName,Email,Mobile,client_CreateDate as CreateDate ";
                    strQuery = context.Request.Params["strQuery"].ToString();
                    strGroupType = context.Request.Params["strGroupType"].ToString();
                    strGroupName = context.Request.Params["GroupName"].ToString();
                    strdays = context.Request.Params["strdays"].ToString();
                    if (strdays == "30")
                        strdays = " DATEDIFF(CURDATE(),DATE(EditDate)) <= 30 ";
                    else if (strdays == "90")
                        strdays = "  DATEDIFF(CURDATE(),DATE(EditDate)) <= 90 ";
                    else
                        strdays = string.Empty;

                    if (strGroupType == "Direct Client")
                    {
                        if (!string.IsNullOrEmpty(strdays))
                            strQuery += " AND " + strdays;

                        strQuery += " Group By ContactID";
                        dt = DBhelper.ExecuteDataset(strQuery).Tables[0];
                    }
                    else
                    {

                        if (strGroupType == "EMAIL")
                        {
                            if (strGroupName == "Birthday Emails")
                                strcols = " ContactID,FirstName,SurName,Email,Mobile, PurposeSummary,State";
                            else
                                strcols = " ContactID,FirstName,SurName,Email,Mobile, PurposeSummary,State,CreateDate";
                        }
                        strQuery = strQuery.Replace("*", strcols);
                        if (!string.IsNullOrEmpty(strdays))
                            strQuery += " AND " + strdays;

                        strQuery += " Group By ContactID";
                        dt = DBhelper.ExecuteDataset(strQuery).Tables[0];
                    }
                }

                StreamWriter sw = new StreamWriter(strFilePath, false);
                int iColCount = dt.Columns.Count;

                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                        sw.Write(",");
                }
                sw.Write(sw.NewLine);

                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                            sw.Write(dr[i].ToString());
                        if (i < iColCount - 1)
                            sw.Write(",");
                    }
                    sw.Write(sw.NewLine);
                }
                sw.Close();

                FileInfo fi = new FileInfo(strFilePath);
                if (fi.Exists)
                {
                    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fi.Name);
                    HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
                    HttpContext.Current.Response.ContentType = "application/.csv";
                    HttpContext.Current.Response.TransmitFile(strFilePath);
                    HttpContext.Current.Response.Flush();
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("Error");
                ErrorHandler.saveErrorLog(ex, CMSContext.CurrentUser.MemberName);
            }
            if (strReportName == "Test2014")
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("/ExportGroupData/reportTest2014.csv"));
            else if (strReportName == "GroupData")
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("/ExportGroupData/groupdata.csv"));

            HttpContext.Current.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}